<?php
// @todo flashmessager should finally show something!
class IndexController extends Zgm_Controller_Base {

public function init() {
    /* Initialize action controller here */
}
public function testAction() {
    $this->_helper->FlashMessenger->setNamespace('messages')->addMessage('Hey, congrats!');

}
public function indexAction() {
//       $identity = Zend_Auth::getInstance()->getIdentity();
//   $this->_helper->layout()->disableLayout();
//   var_dump(APPLICATION_PATH.'views/scripts/');die;
//   $placeModel =  new Model_Places();
//  var_dump($placeModel->getAllPlacesInXML($identity['id']));
   //$this->_helper->FlashMessenger->setNamespace('messages')->addMessage('Congrats!');
      $this->_redirect('/index/test');

//   $acl = new Zgm_Access_ModelAcl();
//   $heh = $acl->isAllowed('guest', 'index', 'index');
//   
//$requestedAddress = 'Kyev';
//$geocoder = new Zgm_Geo_Geocoder();
//$responceAddress = $geocoder->lookup($requestedAddress);
//foreach ($responceAddress as $key=>$addressItem) {
//  $coordinates = $addressItem->getPoint();
//  $lat = $coordinates->getLatitude();
//  $lng = $coordinates->getLongitude();
//  $address = $addressItem->getAddress();
//}
//if(isset($address)) {
//   switch ((count(explode(',', $address))) {
//      case 5:
//         list($street, $city, $state, $country, $index) = explode(',', $address);
//         break;
//      case 4:
//         list($street, $city, $country, $index) = explode(',', $address);
//         break;
//      case 3:
//         list($street, $city, $state, $country, $index) = explode(',', $address);
//         break;
//      case 2:
//         list($street, $city, $state, $country, $index) = explode(',', $address);
//         break;
//      case 1:
//         list($street, $city, $state, $country, $index) = explode(',', $address);
//         break;
//      default:
//         break;
//   }


}
public function getMarkersAction() {
   $identity = Zend_Auth::getInstance()->getIdentity();
   $this->_helper->layout()->disableLayout();
   $placeModel =  new Model_Places();
   echo $placeModel->getAllPlacesInXML($identity['id']);
}

public function registerAction() {
    $flashMessenger = $this->_helper->getHelper('FlashMessenger');
    $flashMessenger->addMessage('We did something in the last request');

    $form = new Form_Register();
    $this->view->form = $form;

    if ($this->_request->isPost()) {
        if($form->isValid($this->_request->getPost())){
           $args = array();
           $args = $form->getValues();
           $requestedAddress = $args['location'];
           // Location processing
           $geocoder = new Zgm_Geo_Geocoder();
           $responceAddress = $geocoder->lookup($requestedAddress);
           foreach ($responceAddress as $key=>$addressItem) {
              $coordinates = $addressItem->getPoint();
              $lat = $coordinates->getLatitude();
              $lng = $coordinates->getLongitude();
              $address = $addressItem->getAddress();
           }
           //When the geocoder returns results, it places them within a (JSON) results array. 
           //Even if the geocoder returns no results (such as if the address doesn't exist) it still returns an empty results array.
           //(XML responses consist of zero or more <result> elements.)
           if (isset($address)) {
              // Home location user points while registretaion will not ever be used through out
              // the site for security purposes. Might be used for any kind of statistics.
              // @todo use this point as a centre when open map?
              $args['place'] = array('title' => 'Home',
                                     'user_id' => 0,
                                     'location' => serialize(explode(',', $address)),
                                     'lat' => $lat,
                                     'lng' => $lng,);
              $placeModel =  new Model_Places();
              $placeId = $placeModel->add($args['place']);

              $args['location'] = $placeId;
              $userModel = new Model_Users();
              $userId= $userModel->add($args);

              if ($userId) {
                $flashMessenger->addMessage('You have been registered successfully. Login using your credentials, please.');
                $this->_redirect('/');
              } else {
               // @todo really, need to do something when incorrect data is typed
               syslog(LOG_WARNING, 'No data found for address requiested: '.$requestedAddress);
           }
        }
    }
}
}

public function loginAction() {

    $this->_helper->layout()->disableLayout();
    
    // if user isn't logged
    if (!Model_Users::isLogged()) {
    $form = new Form_Login();
    $this->view->form = $form;
    
    if ($this->_request->isPost()) {
        $filter = new Zend_Filter_HtmlEntities(ENT_NOQUOTES, 'UTF-8');
        $email = $filter->filter($this->getRequest()->getParam('email'));
        $password = md5($this->getRequest()->getParam('password'));
        $dbAdapter = Zend_Db_Table_Abstract::getDefaultAdapter();
        $authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter);
        $authAdapter
                ->setTableName('users')
                ->setIdentityColumn('email')
                ->setCredentialColumn('password');
        // Strip slashes because POST adds slashes, but Zend table adds slashes also.
        $authAdapter
                ->setIdentity(stripslashes($email))
                ->setCredential(stripslashes($password));
        $result = $authAdapter->authenticate();
        // If there are any problems while login.
           if (!$result->isValid()) {
              switch ($result->getCode()) {
                 case Zend_Auth_Result::FAILURE_IDENTITY_NOT_FOUND:
                   // Non-existent identity
                    $this->_errors[] = 'User doesn\'t exist.';
                    break;
                 case Zend_Auth_Result::FAILURE_CREDENTIAL_INVALID:
                   // Incorrect credentials
                    $this->_errors[] = 'Authorization error. Please, check login or/and password';
                    break;
                 default:
                   // Other errors
                   $this->_errors[] = 'Login is failed due to unknown reasons. Please, try again.';
                   break;
              }
           } elseif ($result->getCode() == Zend_Auth_Result::SUCCESS) {
               $userData = $authAdapter->getResultRowObject();
               // $role = getRole from database. set public rule as default one.
               Zend_Auth::getInstance()->getStorage()->write(array('id' => $userData->id,
                                                                   'role_id' => '1',
                                                                   'email' => $userData->email,));
//             Zend_Auth::getInstance()->getStorage()->read();

                $this->_redirect('/');
           }
       if(isset($this->_errors)) {
          $this->view->errors = $this->_errors;
       }
    }

   } else {
   $this->_redirect('/');
   }

   }

   public function logoutAction(){
       Model_Users::logout();
       Zend_Session::forgetMe();
       $this->_redirect('/');
   }

}